import threading


# 懒汉式单例：首次使用时才创建实例，双重检查锁确保线程安全
class SingletonLazy:
    _instance = None
    _lock = threading.Lock()  # 锁对象

    def __new__(cls):
        # 第一次检查：如果实例已存在，直接返回
        if cls._instance is None:
            # 加锁
            with cls._lock:
                # 第二次检查：防止多个线程同时通过第一次检查后重复创建实例
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
        return cls._instance


# 测试多线程环境下的单例
def test_lazy_singleton():
    def worker():
        s = SingletonLazy()
        print(f"线程 {threading.current_thread().name} 实例地址: {id(s)}")

    threads = []
    for i in range(5):
        t = threading.Thread(target=worker, name=f"Thread-{i}")
        threads.append(t)
        t.start()

    for t in threads:
        t.join()


if __name__ == "__main__":
    print("懒汉式 - 多线程测试:")
    test_lazy_singleton()
    s1 = SingletonLazy()
    s2 = SingletonLazy()
    print(f"懒汉式 - s1和s2是否为同一实例: {s1 is s2}")  # 输出 True